package ExcelTools

import (
	"fmt"
	"net/http"

	"github.com/zeromicro/go-zero/rest/httpx"
	"property_api/internal/logic/excel/ExcelTools"
	"property_api/internal/svc"
	"property_api/internal/types"
)

func DownloadHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.ExcelToolsFrom
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		l := ExcelTools.NewDownloadLogic(r.Context(), svcCtx)
		resp, err := l.Download(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			// 设置 HTTP 响应头
			// 设置 HTTP 响应头
			w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") // Excel 文件类型
			w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s.xlsx", req.TableName))   // 文件下载提示
			w.Header().Set("Content-Length", fmt.Sprintf("%d", len(resp.Data)))                                 // 响应体长度 // 设置文件大小

			// 将二进制数据写入响应流
			w.Write(resp.Data)
		}
	}
}
